package com.computer.network.service.serviceImpl;

import com.computer.network.mapper.UserMapper;
import com.computer.network.properties.JwtProperties;
import com.computer.network.service.UserService;
import com.computer.network.entity.vo.ResponseVO;
import com.computer.network.entity.vo.UserVO;
import com.computer.network.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private JwtProperties jwtProperties;

    private final static String ACCOUNT_EXIST = "账号已存在";
    private final static String ACCOUNT_NOT_EXIST = "账号不存在";
    private final static String ACCOUNT_INFO_ERROR = "用户名或密码错误";

    @Autowired
    UserMapper userMapper;

    /**
     * 注册用户
     * @param userVO 用户信息
     * @return 注册结果
     */
    @Override
    public ResponseVO addUser(UserVO userVO) {
        try {
            //对密码进行MD5加密
            userVO.setPassword(
                    DigestUtils.md5DigestAsHex(userVO.getPassword().getBytes()));
            //添加用户信息
            userMapper.addUser(userVO);
            return ResponseVO.buildSuccess();
        } catch (Exception e) {
            //如果添加失败，返回错误信息
            System.out.println(e.getMessage());
            return ResponseVO.buildFailure(ACCOUNT_EXIST);
        }
    }

    /**
     * 登录用户
     * @param userVO 用户信息
     * @return 登录结果
     */
    @Override
    public ResponseVO login(UserVO userVO) {
        //根据用户名查询用户信息
        UserVO foundUser = userMapper.getUserByName(userVO.getName());
        //判断用户是否存在
        if (foundUser == null) {
            return ResponseVO.buildFailure(ACCOUNT_NOT_EXIST);
        }

        //对密码进行MD5加密并验证
        String resPassword = DigestUtils
                .md5DigestAsHex(userVO.getPassword().getBytes());
        String dbPassword = foundUser.getPassword();
        if (!resPassword.equals(dbPassword)) {
            return ResponseVO.buildFailure(ACCOUNT_INFO_ERROR);
        }

        //密码验证通过后，生成JWT token
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", foundUser.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        foundUser.setToken(token);

        //登录成功，返回用户信息
        return ResponseVO.buildSuccess(foundUser);
    }
}
